/*
Copyright (C) Ariff Ehsan, Abdul Hadi Fikri

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

/*  Author : Ariff Ehsan
 *  Date   : June 29, 2009
 */


#include <system.h>

timer_t app_timer;

message_t app_msg;
BOOL app_busy = FALSE;

void APP_TIMER_run(void);

void APP_CXBEE_startDone(error_t);
void APP_CXBEE_sendDone(error_t);
message_t *APP_CXBEE_receive(message_t *msg, void *payload, uint8_t len);

void APP_ADC_readDone(uint16_t);

void APP_booted(){
	
	/* initialize leds */
	DDRC |= (0x1e);
	
	/* register timer */
	TIMER_reg(&app_timer, APP_TIMER_run);
	
	CXBEE_reg(APP_CXBEE_startDone, APP_CXBEE_sendDone, APP_CXBEE_receive);
	CXBEE_start();
	
	ADC_init();
	ADC_reg(APP_ADC_readDone);
}

void APP_TIMER_run(void) {
}

void APP_CXBEE_startDone(error_t error) {
	
	/* start periodic timer */
	
	if (error != SUCCESS) {
		PORTC |= (1<<PC4);
		return;
	}
	
	ADC_read(0);
}

void APP_CXBEE_sendDone(error_t error) {
	
	app_busy = FALSE;
	
	ADC_read(0);
	PORTC ^= (1<<PC3);
}

message_t *APP_CXBEE_receive(message_t *msg, void *payload, uint8_t len) {
	return msg;
}

void APP_ADC_readDone(uint16_t result) {
	
	if (app_busy) {
		PORTC |= (1<<PC4);
		return;
	}
	
	app_busy = TRUE;
	
	/* config test packet */
	CXBEE_setTxPower(&app_msg, CXBEE_DEF_TXPOWER); // max power level
	CXBEE_setAck(&app_msg, TRUE);  // enable ack
	
	/* get payload pointer */
	uint8_t *payload = (uint8_t *)(CXBEE_getPayload(&app_msg));
	
	payload[0] = result >> 8;
	payload[1] = result;
	
	error_t error = CXBEE_send(CXBEE_BCAST_ADDR, &app_msg, 2);
}
